package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.enums.UserRealnameStatus;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>
        implements ApUserRealnameService {
    /**
     * 按照状态分页查询用户列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //检查参数
        if (null==dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //参数合理化
        dto.checkParam();

        LambdaQueryWrapper<ApUserRealname> wrapper =new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> page=new Page<>(dto.getPage(),dto.getSize());
        IPage<ApUserRealname> res = page(page, wrapper);
        ResponseResult<List<ApUserRealname>> responseResult =
                new PageResponseResult<>((int)res.getPages(),(int)res.getSize(),(int)res.getTotal());
        responseResult.setData(res.getRecords());
        return responseResult;
    }

    /**
     * 根据状态进行审核
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public ResponseResult updateStatusById(AuthDto dto) {
        //1.检查参数
        if(dto == null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查状态
        if(!UserRealnameStatus.isDefined(dto.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(UserRealnameStatus.get(dto.getStatus()));
        if(dto.getMsg() != null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //3.如果审核状态是通过，创建自媒体账户，创建作者信息
        if(apUserRealname.getStatus()==UserRealnameStatus.PASS_AUTH){
            //创建自媒体账户，创建作者信息
            ResponseResult result = createWmUserAndAuthor(dto);
            if(result != null){
                return result;
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ApUserMapper apUserMapper;
    /**
     *  创建自媒体账户，创建作者信息
     * @param dto
     */
    private ResponseResult createWmUserAndAuthor(AuthDto dto){
        //获取ap_user信息
        Integer apUserRealnameId = dto.getId();
        log.debug("审核列表ID="+dto.getId());
        ApUserRealname apUserRealname = getById(apUserRealnameId);
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        log.debug("用户信息："+apUser);
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ResponseResult<WmUser> res = new ResponseResult<>();
        try {
            res = wemediaFeign.findByName(apUser.getName());
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("apUser.getName()"+apUser.getName());
        }
        WmUser  wmUser=res.getData();
        if(wmUser == null){
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            ResponseResult result = wemediaFeign.save(wmUser);
            if (result.getCode()!=AppHttpCodeEnum.SUCCESS.getCode()){
                throw new RuntimeException("保存自媒体用户信息失败");
            }
        }
        //创建作者
        createAuthor(wmUser);
        apUser.setFlag((short)1);//用户标记 0 普通用户  1 自媒体人  2 大V
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 创建作者
     * @param wmUser
     */
    @Autowired
    private ArticleFeign articleFeign;

    private void createAuthor(WmUser wmUser) {
        log.debug("自媒体用户信息:"+wmUser);
        Integer apUserId = wmUser.getApUserId();
        ResponseResult<ApAuthor> res = articleFeign.findByUserId(apUserId);
        ApAuthor apAuthor = res.getData();
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            apAuthor.setType(2);//用户标记  0 爬取数据  1 签约合作商  2 平台自媒体人
            ResponseResult result = articleFeign.save(apAuthor);
            if (result.getCode()!=AppHttpCodeEnum.SUCCESS.getCode()){
                throw new RuntimeException("保存APP文章作者信息失败");
            }
        }
    }

}
